#include "../../server/mq_comsumer.hpp"
#include <iostream>
#include <gtest/gtest.h>

using namespace xzt;

ConsumerManager::ptr p_em;

class ConsumerTest: public testing::Environment
{
    virtual void SetUp() override
    {
        p_em = std::make_shared<ConsumerManager>();
        p_em->declareQueueConsumer("queue1");
    }

    virtual void TearDown() override
    {
        p_em->clear();
    }
};

void cb(const std::string& tag, const xzt::BasicPropeties* bp, const std::string& body)
{
    std::cout << tag << " 消费了消息: " << body << std::endl;
}

TEST(consumer_test, insert_test)
{
    p_em->create("consumer1", "queue1", true, cb);
    p_em->create("consumer2", "queue1", true, cb);
    p_em->create("consumer3", "queue1", true, cb);

    EXPECT_TRUE(p_em->exist("consumer1", "queue1"));
    EXPECT_TRUE(p_em->exist("consumer2", "queue1"));
    EXPECT_TRUE(p_em->exist("consumer3", "queue1"));
}

TEST(consumer_test, choose_test)
{
    // choose 是轮询算法
    Consumer::ptr pc = p_em->choose("queue1");
    EXPECT_NE(nullptr, pc);
    EXPECT_EQ("consumer1", pc->_tag);

    pc = p_em->choose("queue1");
    EXPECT_NE(nullptr, pc);
    EXPECT_EQ("consumer2", pc->_tag);

    pc = p_em->choose("queue1");
    EXPECT_NE(nullptr, pc);
    EXPECT_EQ("consumer3", pc->_tag);
    
    pc = p_em->choose("queue1");
    EXPECT_NE(nullptr, pc);
    EXPECT_EQ("consumer1", pc->_tag);
}

TEST(consumer_test, remove_test)
{
    p_em->remove("consumer1", "queue1");
    EXPECT_FALSE(p_em->exist("consumer1", "queue1"));
    EXPECT_TRUE(p_em->exist("consumer2", "queue1"));

    p_em->remove("consumer2", "queue1");
    EXPECT_FALSE(p_em->exist("consumer1", "queue1"));
    EXPECT_FALSE(p_em->exist("consumer2", "queue1"));
}




int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    testing::AddGlobalTestEnvironment(new ConsumerTest);
    
    return RUN_ALL_TESTS();
}


